package com.hzh.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionUtil {
	
    public static RuntimeException unchecked(Exception e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        } else {
            return new RuntimeException(e);
        }
    }
    
    public static String getStackTraceAsString(Exception e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
    
    public static String getErrorMessageWithNestedException(Exception e) {
        Throwable nestedException = e.getCause();
        return new StringBuilder().append(e.getMessage()).append(" nested exception is ")
            .append(nestedException.getClass().getName()).append(":")
            .append(nestedException.getMessage()).toString();
    }
    
    @SuppressWarnings("unchecked")
    public static boolean isCausedBy(Exception ex,
        Class<? extends Exception>... causeExceptionClasses) {
        Throwable cause = ex;
        while (cause != null) {
            for (Class<? extends Exception> causeClass : causeExceptionClasses) {
                if (causeClass.isInstance(cause)) {
                    return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }
    
    public static String getExceptionMsg(Exception e) {
        return e.getMessage().length() < 100 ? e.getMessage() : "后台处理异常!"; 
    }
}
